import { omitBy } from 'lodash-unified'
import { type Ref, computed } from 'vue'

import { dictApi } from '@/apis'
import { TableRefHook, useDialog } from '@/hooks'
import { download } from '@/utils'

import { useDictTypeForm } from '.'

type Params = {
  selectedIds: Ref<Set<string>>
  tableRefHook: TableRefHook
}

export function useToolbar({ selectedIds, tableRefHook }: Params) {
  const canExport = computed(() => {
    if (tableRefHook.tableRef.value) {
      return tableRefHook.tableRef.value.getData().length > 0
    }
    return false
  })

  const { showConfirm } = useDialog()
  const {
    show: showAdd,
    loading: addLoading,
    formModel: addFormModel,
    formRef: addFormRef
  } = useDictTypeForm()

  function handleShowAdd() {
    showAdd.value = true
  }

  function handleAdd() {
    addFormRef.validate().then(async () => {
      try {
        addLoading.value = true

        await dictApi.createDictType(addFormModel.value)

        addLoading.value = false
        handleCloseAdd()
        tableRefHook.refresh()
      } catch {
        addLoading.value = false
      }
    })
  }

  function handleCloseAdd() {
    showAdd.value = false
  }

  function handleDeleteList() {
    showConfirm({
      content: '确认删除？',
      onOk: async () => {
        await dictApi.deleteDictType({
          ids: Array.from(selectedIds.value)
        })

        selectedIds.value.clear()
        tableRefHook.refresh()
      }
    })
  }

  async function handleExport() {
    const { form, pager } = tableRefHook.tableRef.value.getProxyInfo()!

    const dto = omitBy(form, value => {
      return value === null
    })

    try {
      tableRefHook.showLoading()

      const res = await dictApi.exportDictTypePage({
        pageSize: pager.pageSize,
        pageNum: pager.currentPage,
        ...dto
      } as any)

      download(res)
    } finally {
      tableRefHook.hideLoading()
    }
  }

  return {
    canExport,
    showAdd,
    addLoading,
    addFormModel,
    addFormRef,
    handleShowAdd,
    handleAdd,
    handleCloseAdd,
    handleDeleteList,
    handleExport
  }
}
